package org.pp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.pp.core.Assertion;
import org.pp.core.BizErro;
import org.pp.core.BizExcept;
import org.pp.entity.PpPublicFile;
import org.pp.mapper.PpPublicFileMapper;
import org.pp.service.IPpPublicFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.pp.store.OssStore;
import org.pp.vo.PublicFileVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;

/**
 * <p>
 * 文件表 服务实现类
 * </p>
 *
 * @author haima
 * @since 2024-06-02
 */
@Service
public class PpPublicFileServiceImpl extends
        ServiceImpl<PpPublicFileMapper, PpPublicFile> implements IPpPublicFileService {
    @Autowired
    OssStore ossStore;

    @Override
    @Transactional
    public PublicFileVo upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String extName = FileUtil.extName(originalFilename);
        Assertion.blankThrow(extName,"扩展名不符合");
        //pp-shop-study/text.txt
        PpPublicFile publicFile= new PpPublicFile();
        String fileName = IdUtil.fastSimpleUUID();
        String month= DateUtil.format(new Date(),"yyyyMM");
        String path= StrUtil.format("{}/{}.{}",month,fileName,extName);
        String md5 =null;
        try {
             md5 = SecureUtil.md5(Arrays.toString(file.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            throw BizExcept.erro("上传失败");
        }
        PpPublicFile one = getOne(new LambdaQueryWrapper<PpPublicFile>().eq(PpPublicFile::getMd5, md5));
        if(Objects.isNull(one)){
            ossStore.upload(file,path);
            publicFile.setPath(path);
            publicFile.setFileType(extName);
            publicFile.setSize(file.getSize());
            publicFile.setMd5(md5);
            save(publicFile);
            one=publicFile;
        }
        //文件已经上传过了，直接返回信息
        PublicFileVo publicFileVo = BeanUtil.copyProperties(one, PublicFileVo.class);
        publicFileVo.setUrl(ossStore.getUrl(one.getPath()));
        return publicFileVo;
    }
}
